package xyz.luxiaoxiang.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

/**
 * Created by luxx on 2018/3/28 0028.
 */
@Service
public class TuLingService {

    private final static String TULING_API_URL = "http://openapi.tuling123.com/openapi/api/v2";

    private final static String TULING_API_KEY = "117cab9ad0534cf0ae90d0948c13790d";

    private final static String TULING_USERID = "148402";

    /**
     * 图灵机器人 聊天接口
     */
    public String chat(String msg) {
        try {
            JSONObject input = new JSONObject();
            JSONObject perception = new JSONObject();
            JSONObject userInfo = new JSONObject();
            JSONObject inputText = new JSONObject();
            input.put("perception", perception);
            input.put("userInfo", userInfo);
            perception.put("inputText", inputText);
            inputText.put("text", msg);
            userInfo.put("apiKey", TULING_API_KEY);
            userInfo.put("userId", TULING_USERID);


            HttpPost post = new HttpPost(TULING_API_URL);
            post.setEntity(new StringEntity(input.toJSONString(), "application/json", "UTF-8"));
            CloseableHttpResponse response = HttpClientBuilder.create().build().execute(post);
            JSONObject output = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8").trim());
            JSONArray results = JSONArray.parseArray(output.getString("results"));
            System.out.println(output);
            StringBuffer sb = new StringBuffer();
            for (Object obj : results) {
                JSONObject result = (JSONObject) obj;
                JSONObject values = JSONObject.parseObject(result.getString("values"));
                String url = values.getString("url");
                if (url != null) {
                    sb.append(url).append("\n");
                }
                String text = values.getString("text");
                if(text != null){
                    sb.append(text).append("\n");
                }
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
